package com.example.linxilite.network

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener

class ChatWebSocketClient (
    private val onMessageReceived: (String) -> Unit
){
    private var webSocket: WebSocket? = null
    private val client = OkHttpClient()

    fun connect(){
        val request = Request.Builder()
            .url("wss://echo.websocket.org") // 测试服务器：自动回显消息
            .build()

        webSocket = client.newWebSocket(request, object : WebSocketListener(){
            override fun onOpen(ws: WebSocket, response: Response) {
                Log.d("WebSocket", "Connected ✅")
            }

            override fun onMessage(ws: WebSocket, text: String) {
                onMessageReceived(text)
            }

            override fun onFailure(ws: WebSocket, t: Throwable, response: Response?) {
                Log.e("WebSocket", "Error: ${t.message}")
            }
        })
    }

    fun sendMessage(message: String) {
        webSocket?.send(message)
    }

    fun close() {
        webSocket?.close(1000, null)
    }
}